package com.umeox.watch.moto.chat.utils;

import static com.umeox.moto.common.utils.FileUtils.closeIO;

import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.Toast;

import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.moto.common.utils.AndroidUtils;
import com.umeox.watch.moto.chat.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

public class ImageUtil {

    public static final int QUALITY = 50;
    public static final Bitmap.CompressFormat FORMAT = Bitmap.CompressFormat.JPEG;


    public static Uri saveImageFile(Context context, String path, byte[] data, boolean needRotate) {
        final BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap source = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
        if (needRotate) {
            Matrix matrix = new Matrix();
            matrix.postScale(-1, 1);
            source = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
        }

        String name = DateFormat.format("yyyyMMddkkmmss", System.currentTimeMillis()).toString() + ".jpg";
        File file = new File(path, name);
        if (bitmapToFile(file, source, context) == null) {
            return null;
        }
        return saveToDataBase(context, file);
    }

    public static File bitmapToFile(File dir, Bitmap bitmap, Context context) {

        FileOutputStream fos = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(FORMAT, QUALITY, bos);
        final int size = bos.size();
        try {
            fos = new FileOutputStream(dir);
            fos.write(bos.toByteArray());
            fos.flush();

        } catch (Exception e) {
            if (size > AndroidUtils.getAvailableInternalMemory()) {
                UToast.showCustomToast(context, R.string.low_memory, Toast.LENGTH_LONG);
            }
            Log.e("Camera", "bitmapToFile: ", e);
            dir = null;
        } finally {
            closeIO(fos);
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
        return dir;
    }

    private static Uri saveToDataBase(Context context, File file) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

}
